package com.leyou.user.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AppTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProp;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的app的token
        String token = request.getHeader(LyConstants.APP_TOKEN_HEADER);
        //判空
        if(StringUtils.isEmpty(token)){
            log.info("【服务之间鉴权】访问失败，来访服务器没有携带token，不能继续访问处理器！");
            return false;
        }
        //解析token
        Payload<AppInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), AppInfo.class);
        }catch (Exception e){
            log.info("【服务之间鉴权】访问失败，token不合法，不能继续访问处理器！");
            return false;
        }
        //获取来访服务可以访问发服务器列表
        List<Long> targetList = payload.getUserInfo().getTargetList();
        //判断当前服务器的id是否在访问目标服务的id集合中
        if(!targetList.contains(jwtProp.getApp().getId())){
            log.info("【服务之间鉴权】访问失败，来访服务没有访问权限，不能继续访问处理器！");
            return false;
        }
        return true;
    }
}
